// sort.cpp : Defines the entry point for the console application.
//

//#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <vector>
//#include <iostream>
//#include <algorithm>

//#include <sys/types.h>
#include <sys/stat.h>
//#include <sys/mman.h>
#include <fcntl.h>
//#include <unistd.h>
//#include <assert.h>
//#include <errno.h>
#include <string.h>
#include <conio.h>
#include <tchar.h>

std::vector<int> array;
FILE *in, *out;
void sort(std::vector<int> &a)
{
    int i,j;
    int n=a.size();
  for(i=0 ; i<n ; i++) {
    for(j = 0 ; j <n-i-1 ; j++) {
      if(a[j] > a[j+1]) {
        int tmp = a[j+1];
        a[j+1] = a[j];
        a[j] = tmp;
      }
    }
  }
}

void getnumbers()
{

  char c;
  char str[10];
  int len=0;
  while ((c=fgetc(in))!=EOF)
  {
      if (c!=',')
      {
          str[len]=c;
          len++;
        //  printf("%s",s[len-1]);
          //s="";
      }
      else
      {
          int k=atoi(str);
          //printf("%d ",k);
          array.push_back(k);
          memset(str,' ',10);
          len=0;
      }
  }
}

int main(int argc, char* argv[]) {
  int i, j, n;
  //in=fopen("in.csv","r");
  //out=fopen("out.csv","w");
   int input = open("in.csv", O_RDWR);
  struct stat file_stat;
  int size=fstat(input,&file_stat);
  // printf("%d",file_stat.st_size);
  HANDLE hFileMapping;
  HANDLE hFile;
  hFile = CreateFile("\sort.cpp",               // file to open
                       GENERIC_READ,          // open for reading
                       FILE_SHARE_READ,       // share for reading
                       NULL,                  // default security
                       OPEN_EXISTING,         // existing file only
                       FILE_ATTRIBUTE_NORMAL, // normal file
                       NULL);                 // no attr. template

 if (hFile == INVALID_HANDLE_VALUE)
    {
        printf("Could not open file (error %d)\n", GetLastError());
        return 4;
    }
  LPCTSTR pBuf;

  hFileMapping = CreateFileMapping(
  hFile,
  NULL,
  PAGE_READWRITE,
  0,
  256,
  "Global\\MyFileMappingObject");
 if (hFileMapping == NULL)
   {
      printf(TEXT("Could not create file mapping object (%d).\n"),
             GetLastError());
      return 1;
   }

  getnumbers();
  sort(array);
  for(i=0 ;i<array.size() ;i++) {
    fprintf(out,"%d ", array[i]);
  }
  //fclose(in);
  //fclose(out);
  return 0;
}

